{include file="public/header" /}

<body>
<div class="layui-fluid">


    <div class="layui-card" >

        <!--tab标签-->
        <div style="padding: 20px; background-color: #F2F2F2;">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md4">
                    <div class="layui-card">
                        <div class="layui-card-header">组织架构</div>
                        <div class="layui-card-body">
                            <div id="companydeptList" class="demo-tree-more"></div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md8">
                    <div class="layui-card">
                        <div class="layui-card-header">
                            <button type="button" class="layui-btn layuiadmin-btn-role" data-type="add">新建员工</button>
                            <!--<button type="button" class="layui-btn layuiadmin-btn-dept" data-type="adddept">创建公司/部门</button>-->
                        </div>
                        <div class="layui-card-body">
                            <script type="text/html" id="barDemo">
                                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" >删除</a>
                            </script>

                            <table class="layui-hide" id="stafflist" lay-data="" lay-filter="stafflist"></table>

                        </div>
                    </div>
                </div>

            </div>
        </div>


        <form  class="layui-form" action="" id="staffform" style="display: none" lay-filter="formdata">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-inline">
                    <input type="text" name="username" lay-filter="username" lay-verify="username" id="username" autocomplete="off" placeholder="用户名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-filter="name" lay-verify="username" id="name" autocomplete="off" placeholder="姓名" class="layui-input">

                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-inline">
                    <input type="text" name="password" lay-filter="password" lay-verify="password" id="password" autocomplete="off" placeholder="密码" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">是否为部门主管</label>
                <div class="layui-input-inline">
                    <input type="checkbox" id="is_executive" name="is_executive" value="" lay-skin="switch" lay-text="是|否" lay-filter="startDemo" >
<!--                    <input type="checkbox"  name="open" lay-skin="switch" lay-filter="switch" lay-text="ON|OFF">-->
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">公司部门</label>
                <div class="layui-input-inline">
                    <div class="layui-form-select downpanel">
                        <div class="layui-select-title"><input id="chooseName" lay-filter="chooseName" type="text" placeholder="请选择部门" value="" class="layui-input">
                            <input type="hidden"  lay-filter="chooseID"  id="chooseID" value="">
                            <input type="hidden"  lay-filter="companyid"  id="companyid" value="">
                            <i class="layui-edge"></i></div>
                        <dl class="layui-anim layui-anim-upbit">
                            <dd>
                                <div id="fieldtree" class="demo-tree-more"></div>
                            </dd>
                        </dl>
                    </div>
                    <!--<input type="text" name="fieldname" id="fieldname" value="" placeholder="输入字段名称" class="layui-input">-->
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">上传头像</label>
                    <div class="layui-input-inline">
                        <div class="layui-upload-drag" id="test10">
                            <i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>
                            <div class="layui-hide" id="uploadImg">
                                <hr>
                                <img src="" alt="上传成功后渲染" style="max-width: 196px">
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        </form>

    </div>

</div>

{include file="public/footer" /}

<style>

    /* 防止下拉框的下拉列表被隐藏---必须设置--- */
    .layui-table-cell {overflow: visible !important;}
    /* 使得下拉框与单元格刚好合适 */
    td .layui-form-select{
        margin-top: -10px;
        margin-left: -15px;
        margin-right: -15px;
    }
    /*由于layui 设置了超出隐藏，点击下拉框被table覆盖，所以这里改变下，以兼容操作按钮的下拉菜单*/
      .layui-table-body,.layui-table-box,.layui-table-cell {
        overflow: visible !important;
    }

</style>
<script>
    //var table = null;
     layui.use(['element','laydate','table','form','tree','upload'], function(){
        var table = layui.table;
        var tree = layui.tree
            ,layer = layui.layer
            ,form = layui.form
            ,upload = layui.upload;

        //监听指定开关
        form.on('switch(switch)', function(data){
            layer.msg('开关checked：'+ (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });
            layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
        });

        //拖拽上传
        upload.render({
            elem: '#test10'
            ,url: "{:url('/comm/upload/uploadimg')}" //改成您自己的上传接口
            ,done: function(res){
                console.log(res)
                layer.msg('上传成功');
                layui.$('#uploadImg').removeClass('layui-hide').find('img').attr('src', res.data);
                console.log(res)
            }
        });



        var treedata = [];
        $.ajax({
            url: "{:url('Organization/getDeptList')}",
            data: '',
            success: function (e) {
                console.log(e)
                treedata = e.data;
                console.log(treedata);
                //无连接线风格
                tree.render({
                    elem: '#companydeptList'
                    ,data: treedata
                    ,accordion: true //手风琴模式
                    ,showLine: false  //是否开启连接线
                    ,none: '无数据' //数据为空时的提示文本
                    ,edit: ['add', 'update', 'del'] //操作节点的图标
                    ,id:'demoId'
                    ,operate: function(obj){
                        var type = obj.type; //得到操作类型：add、edit、del
                        var data = obj.data; //得到当前节点的数据
                        var elem = obj.elem; //得到当前节点元素

                        //Ajax 操作
                        var id = data.id; //得到节点索引
                        if(type === 'add'){ //增加节点
                            //addtept();
                            layer.prompt({
                                formType: 0 ////输入框类型，支持0（文本）默认1（密码）2（多行文本）
                                ,title: '添加新部门'
                                ,value: ''
                                ,end: function(index, layero){
                                    //层销毁后触发的回调 也就是取消
                                    return false;
                                }
                            },function(value, index){

                                obj.data.editdepaname = value;
                                obj.data.opert = 'add';
                                addEdittept(data)
                                layer.close(index);

                            });

                            //返回 key 值
                            //return 123;
                        } else if(type === 'update'){ //修改节点
                            //console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
                            obj.data.editdepaname = elem.find('.layui-tree-txt').html();
                            obj.data.opert = 'update';
                            addEdittept(data)

                        } else if(type === 'del'){ //删除节点
                            obj.data.opert = 'del';
                            addEdittept(data)
                        };
                    }
                    ,click: function(obj){
                        var id = obj.data.id;
                        var type = obj.data.type;
                        table.render({
                            id:'dep_table'
                            ,elem: '#stafflist'
                            ,url:"{:url('Organization/ajaxGetstaffList')}"
                            ,page:true
                            ,where:{id:id,type:type}
                            ,cols: [[
                                ,{align:'center',field:'username',title: '用户名'}
                                ,{align:'center',field:'name', title: '姓名'}
                                ,{align:'center',field:'deptname', title: '部门'}
                                ,{align:'center',fixed: 'right', title:'操作', toolbar: '#barDemo'}
                            ]]

                            ,done: function(res, curr, count){

                            }

                        });
                        //getDeptStaffList(table,form,id,type);

//                        console.log(obj.data); //得到当前点击的节点数据
//                        console.log(obj.state); //得到当前节点的展开状态：open、close、normal
//                        console.log(obj.elem); //得到当前节点元素
//
//                        console.log(obj.data.children); //当前节点下是否有子节点
                    }
                });

                //console.log(treedata);

                //渲染tree
                tree.render({
                    elem: '#fieldtree',
                    data: treedata,
                    none: '无数据', //数据为空时的提示文本
                    click: function (obj) {
                        var pid = $('.layui-tree-spread').attr('data-id');//得到当前点击的节点的父级id
                        console.log(obj.data); //得到当前点击的节点数据
                        $("#chooseName").val(obj.data.title);
                        $("#chooseID").val(obj.data.id);
                        $("#companyid").val(obj.data.companyid);
                    }
                });

            }

        })

        //下拉交互显示
        $(".downpanel").on("click", ".layui-select-title", function (e) {

            $(".downpanel").not($(this).parents(".downpanel")).removeClass("layui-form-selected");
            $(this).parents(".downpanel").toggleClass("layui-form-selected");
            layui.stope(e);
        }).on("click", "dl i", function (e) {
            layui.stope(e);
        });
        $(document).on("click", function (e) {
            $(".downpanel").removeClass("layui-form-selected");
        });

        $('.layui-btn.layuiadmin-btn-role').on('click', function(){
            Loadform('新增','add','',table,form)
        });


        //监听行工具事件
        table.on('tool(stafflist)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                var msg = '您确认要删除员工 [ '+ data.name +' ]么?'
                layer.confirm(msg, function(index){
                    data.type = "del";
                    $.ajax({
                        url: "{:url('Organization/ajaxAddUpdataStaff')}",
                        data: data,
                        success: function (e) {
                            if(e.code==1){
                                $(".layui-layer-btn1").click()
                            }
                            layer.msg(e.msg);
                        }

                    });

                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                
                Loadform('编辑','edit',data,table,form)
            }
        });


    });
    //新增编辑删除树节点
    function addEdittept(data) {

        $.ajax({
            url: "{:url('Organization/ajaxAddUpdataDept')}",
            data: data,
            success: function (e) {

                if(data.opert=='add'){
                    treedata = e.data;
                    //重载数据
                    layui.use(['element','tree'], function() {
                        var tree = layui.tree
                            , layer = layui.layer
                        tree.reload('demoId', {
                            data: treedata
                        });

                    });
                }

                layer.msg(e.msg)
            }

        });
    }



    function del(id) {
        $.ajax({
            url: "{:url('Organization/ajaxAddStaff')}",
            data: data,
            success: function (e) {
                layer.msg(e.msg);
            }

        });
    }
    function Loadform(title,type='',data='',table,form) {

        var win = layer.open({
            type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            ,title: title //标题
            //,skin:title   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
            //,area: ['400px', '400px'] //宽度、高度
            ,shade: 0.3
            ,offset: 'auto'
            ,shade: false
            ,anim:1 //弹出动画
            //,shadeClose: true //弹框出现后，允许点击其它地方关闭
            ,maxmin: true //允许最大化
            ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
            ,content: $("#staffform")//内容
            ,btn: ['确定', '取消'] //只是为了演示
            ,yes: function(index, layero){


                var obj = form.val('formdata');
                if(obj.hasOwnProperty('is_executive')){
                   var is_executive = 1;
                }else{
                   var is_executive = 0
                }
                var data1 = {
                    'name' : $.trim($('#name').val()),
                    'dep_id' : $.trim($('#chooseID').val()),
                    'username' : $.trim($('#username').val()),
                    'password' : $.trim($('#password').val()),
                    'imgurl' : $("#uploadImg").find('img').attr('src'),
                    'companyid' : $("#companyid").val(),
                    'is_executive': is_executive,
                }
                if($('#username').val()==''){
                    return layer.msg('用户名不能为空');
                }
                if($('#name').val()==''){
                    return layer.msg('姓名不能为空');
                }
                if($('#chooseID').val()==''){
                    return layer.msg('请选择部门');
                }

                if(type=='edit'){

                    data1.id = data.id
                    data1.type = 'edit'
                }else{
                    data1.type = 'add'
                }
                
                $.ajax({
                    url: "{:url('Organization/ajaxAddUpdataStaff')}",
                    data: data1,
                    success: function (e) {
                        if(e.code==1){
                            $(".layui-layer-btn1").click()
                        }
                        layer.msg(e.msg);
                        table.reload('dep_table', {
                                page: {
                                curr: 1 //重新从第 1 页开始
                                }
                                //,where: {
                                //        id: demoReload.val()
                                //}
                            }, 'data'
                        );
                    }
                    
                });

            }
            ,success: function (layero) {
                console.log(data);
                $('#name').val(data.name)
                $('#username').val(data.username)
                $('#chooseID').val(data.dep_id)
                $('#companyid').val(data.companyid)
                $('#chooseName').val(data.deptname)
                $('#password').val(data.password)
                $("#ckbx").prop("checked",true);
                if(data.is_executive == 1){
                   var is_executive = true;
                }else{
                    var is_executive = false;
                }
                form.val('formdata', {
                    "is_executive": is_executive //开关状态
                });
                layui.$('#uploadImg').removeClass('layui-hide').find('img').attr('src', data.imgurl);
                var mask = $(".layui-layer-shade");
                mask.appendTo(layero.parent());   //其中：layero是弹层的DOM对象
            }
        });

    }
</script>
</body>
</html>
